package com.zy.find;

import java.util.List;

/**
 * __|__ __|__
 * _|_   _|_
 * .---. .---.
 * |___| |___|
 * _\_/_ _\_/_
 * _X_   _X_
 * |   | |   |
 * |___| |___|
 *
 * @Author zhaoyi
 * @date 2020/4/10
 * 二分查找
 */
public class BinarySearchV2<T extends Comparable<? super T>> {

    /**
     * 二分查找
     * 返回数组下标
     */
    public int find(List<T> list, T t) {
        if (t.compareTo(list.get(0)) < 0 || t.compareTo(list.get(list.size() - 1)) > 0) {
            throw new RuntimeException("超出范围找不到");

        }
        return findRecursive(list, t, 0, list.size() - 1);
    }

    private int findRecursive(List<T> list, T t, int left, int right) {
        if (left >= right) {
            if (list.get(left).equals(t)){
                return left;
            }else {
                throw new RuntimeException("找不到");
            }
        }
        //a+(b-a)/2 直接使用(a+b)/2 当a,b很大时超过int的容量
        int mid = left + ((right - left) >> 1);
        if (list.get(mid).compareTo(t) > 0) {
            return findRecursive(list, t, left, mid - 1);
        } else if (list.get(mid).compareTo(t) < 0) {
            return findRecursive(list, t, mid + 1, right);
        } else {
            //return mid;
            //改造下,返回查找第一个值等于给定值的元素
            if (mid == 0 || !list.get(mid - 1).equals(t)) {
                return mid;
            } else {
                return findRecursive(list, t, left, mid);
            }
        }
    }
}
